<template>
  <div v-html="result">
  </div>
</template>

<script setup name="MarkdownIt">
import { onMounted, ref, watchEffect } from'vue'
import MarkdownIt from 'markdown-it'

import hljs from 'highlight.js';

const props = defineProps({
  source: {
    type: String,
    default: ''
  },
  codeTheme: {
    type: String,
    default: 'github'
  }
})

const result = ref('');
const md = MarkdownIt({
  html: true,
  linkify: true,
  highlight: function (str, lang) {

    lang = hljs.getLanguage(lang) ? lang : 'plaintext';
    const highlighted = hljs.highlight(str, { language: lang }).value;

    return `<pre class="code-theme--${props.codeTheme}"><code class="hljs language-${lang}">${highlighted}</code></pre>`;
  }
})

watchEffect(() => {
  result.value = md.render(props.source);
})

onMounted(() => {
  // 手动执行高亮
  // hljs.highlightAll();
})

</script>
